#include "stdafx.h"
#include <Windows.h>
#include <ATLHelper.h>
#include <TlHelp32.h>

struct EnumWinProcParam
{
	DWORD dwProcessId;
	HWND hWindowHandle;
};

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
	EnumWinProcParam* pParam = (EnumWinProcParam*)lParam;
	DWORD processId = 0;
	::GetWindowThreadProcessId(hWnd,&processId);
	if (processId==pParam->dwProcessId)
	{
		const int MAX_LEN = 512;
		TCHAR caption[MAX_LEN];
		::GetWindowText(hWnd,caption,MAX_LEN);

		ATL::CString acadCaption = L"Autodesk AutoCAD";
		ATL::CString captionStr(caption);
		if (captionStr.Left(acadCaption.GetLength()).CompareNoCase(acadCaption)==0)
		{
			pParam->hWindowHandle = hWnd;
			return FALSE;
		}
	}

	return TRUE;
}

int _tmain(int argc, TCHAR* argv[])
{
	if (argc<=1)
	{
		return 0;
	}

	ATL::CString unloadCmd(argv[1]);
	unloadCmd += _T("\r");

	COPYDATASTRUCT cmdMsg;
	cmdMsg.dwData = (DWORD)1;
	cmdMsg.cbData = (DWORD)(unloadCmd.GetLength()+1) * sizeof(TCHAR);
	cmdMsg.lpData = (PVOID)(LPCTSTR)unloadCmd;

	HWND hAcadMainWindow = NULL;
	const ATL::CString acadProcessName = L"acad.exe";
	HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
	if(hSnapshot) 
	{
		PROCESSENTRY32 pe32;
		pe32.dwSize = sizeof(PROCESSENTRY32);
		if(::Process32First(hSnapshot,&pe32)) 
		{
			do 
			{
				ATL::CString processName = pe32.szExeFile;
				if (processName.CompareNoCase(acadProcessName)==0)
				{
					DWORD processId = pe32.th32ProcessID;
					EnumWinProcParam param;
					param.dwProcessId = processId;
					param.hWindowHandle = NULL;
					::EnumDesktopWindows(NULL,EnumWindowsProc,(LPARAM)&param);
					HWND hWnd = param.hWindowHandle;
					if (hWnd!=NULL && ::IsWindow(hWnd))
					{
						//hWnd.GetTopLevelParent();
						HWND hWndParent = hWnd;
						HWND hWndTmp;
						while((hWndTmp = ::GetParent(hWndParent)) != NULL)
							hWndParent = hWndTmp;
						::SendMessage(hWndParent,WM_COPYDATA,NULL,(LPARAM)&cmdMsg);
					}
					break;
				}
			} while(::Process32Next(hSnapshot,&pe32));
		}
		::CloseHandle(hSnapshot);
	}

	return 0;
}


